<template>
  <el-dialog
    :width="1600"
    v-model="formVisible"
    title="新增公示信息"
    @close="formCancel"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-row :gutter="40" style="width: 100%">
        <el-col :span="12">
          <el-form-item label="年份" prop="year">
            <el-date-picker
              v-model="form.year"
              valueFormat="YYYY"
              type="year"
              placeholder="请选择"
              class="select"
              style="width: 480px"
            />
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">-->
        <!--  <el-form-item label="信息来源" prop="dataSource">-->
        <!--    <MSelect v-model="form.dataSource" placeholder="请选择" :options="dataSourceOptions" class="select" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <ElInput v-model="form.title" placeholder="请输入" class="select" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发布机构" prop="org">
            <!--<MTreeSelect-->
            <!--  v-model="form.org"-->
            <!--  placeholder="请选择"-->
            <!--  :data="orgData"-->
            <!--  :fields="{-->
            <!--    value: 'deptName',-->
            <!--    label: 'deptName',-->
            <!--    children: 'children'-->
            <!--  }"-->
            <!--  style="width: 480px"-->
            <!--  :check-strictly="true"-->
            <!--/>-->
            <!--<VirtualTreeDropDown-->
            <!--  v-model="form.org"-->
            <!--  style="width: 480px"-->
            <!--  :options="orgData"-->
            <!--/>-->
            <el-tree-select
              v-model="form.org"
              :data="orgData"
              :props="{
                value: 'deptName',
                label: 'deptName',
                children: 'children'
              }"
              :check-strictly="true"
              placeholder="请选择"
              filterable
              style="width: 480px"
            ></el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发文字号" prop="documentNum">
            <ElInput
              v-model="form.documentNum"
              placeholder="请输入"
              class="select"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效性" prop="effective">
            <ElInput
              v-model="form.effective"
              placeholder="请输入"
              class="select"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="佐证材料" prop="name">
            <MBackingMaterial
              v-model="form.files"
              dateFormat="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容描述" prop="describes">
            <!--<el-input-->
            <!--  v-model="form.describes"-->
            <!--  :rows="2"-->
            <!--  type="textarea"-->
            <!--  placeholder="请输入处理情况"-->
            <!--  input-style="height: 200px"-->
            <!--/>-->
            <m-rich-editor
              v-model="form.describes"
              style="width: 100%"
            ></m-rich-editor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: flex-end; width: 100%">
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="submitForm()" v-loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { msgAddOrUpd, msgDetail } from '@/api/spotCheck/spotCheck'
import { ElMessage } from 'element-plus'
import { dateFormat } from '@/utils'
import db from '@/storage'
const formVisible = ref(false)

onMounted(() => {
  orgData.value = db.get('tree')
  // getTree().then((res: any) => {
  //   orgData.value = res.data
  // })
})

const emit = defineEmits(['reload'])

const dataSourceOptions = ref([
  {
    label: '合格组织抽查',
    value: 0
  },
  {
    label: '风险异常组织抽查',
    value: 1
  },
  {
    label: '社会组织抽查',
    value: 2
  }
])
const orgData: any = ref([])
//新增
const form = reactive({
  files: [],
  title: undefined,
  org: [],
  documentNum: undefined,
  describes: undefined,
  year: undefined,
  dataSource: 0,
  effective: undefined
})

const rules = ref({
  year: [{ required: true, message: '请选择', trigger: 'change' }],
  title: [{ required: true, message: '请输入', trigger: 'change' }],
  org: [{ required: true, message: '请选择', trigger: 'change' }],
  documentNum: [{ required: false, message: '请输入', trigger: 'change' }],
  describes: [{ required: false, message: '请输入', trigger: 'change' }],
  files: [{ required: false, message: '请输入', trigger: 'change' }]
})

const save = () => {
  formVisible.value = true
}

const formCancel = () => {
  formVisible.value = false
}

const show = (id) => {
  clearForm()
  if (id > 0) {
    form.sorgResultPublicityId = id
    msgDetail({ sorgResultPublicityId: id }).then((res) => {
      if (Array.isArray(res.data.files) && res.data.files.length > 0) {
        form.files = res.data.files.map((i) => ({
          fileSum: i.filePage,
          isSave: true,
          name: i.fileName,
          createdAt: dateFormat(i.createTime, 'YYYY-MM-DD'),
          time: i.createTime,
          timestamp: i.createTime,
          isAdd: true,
          file: [
            {
              name: i.fileName,
              status: 'success',
              url: i.fileUrl
            }
          ]
        }))
      } else {
        form.files = []
      }
      form.title = res.data.title
      form.documentNum = res.data.documentNum
      form.describes = res.data.describes
      //这里处理发布机构
      form.org = res.data.org
    })
  }
  formVisible.value = true
}

const PersonnelSelectionRef = ref(false)
//抽检人员
const open = () => {
  PersonnelSelectionRef.value.show()
}

const loading = ref(false)
const ruleFormRef = ref()
const submitForm = () => {
  console.log('form', form)
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    let files = form.files
      .filter((i) => i.isSave)
      .map((i) => {
        let file = {
          fileName: i.name,
          filePage: i.fileSum,
          fileUrl: '',
          createTime: i?.isAdd ? i.time : i.timestamp
        }
        if (Array.isArray(i.file) && i.file.length > 0) {
          //上传了文件
          file.fileName = i.name
          file.fileUrl = i.file[0].url
        }
        return file
      })
    let data = {
      ...form,
      files
    }
    loading.value = true
    msgAddOrUpd(data)
      .then((res) => {
        ElMessage.success(form.sorgSpotCheckId ? '编辑成功' : '提交成功')
        formVisible.value = false
        emit('reload')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const clearForm = () => {
  form.files = []
  form.title = undefined
  form.org = undefined
  form.documentNum = undefined
  form.describes = undefined
  nextTick(() => {
    ruleFormRef.value.resetFields()
  })
}

const resetForm = () => {
  formVisible.value = false
}
defineExpose({ show })
</script>

<style scoped lang="scss">
.search {
  display: flex;
  justify-content: space-between;
}

.btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0;
}

.select {
  width: 480px !important;
}
</style>
